Leetcode-Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

买卖股票的最佳时机,返回最大收益。
Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Description

解题思路
依次遍历整个数组,利用minprice这个变量来保存每个元素之前的最低价格,并计算出在该元素卖出时能够带来的最大收益,最后将每个元素卖出时得到的最大收益进行比较即得到整个系统的最大收益。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxprofit = 0
minprice = float('inf')
for price in prices:
minprice = min(minprice, price)
profit = price - minprice
maxprofit = max(maxprofit, profit)
return maxprofit

tip:
Python中可以用如下方式表示正负无穷:float(“inf”), float(“-inf”)